package com.epam.cdp.selenium2.core.runner.options;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import com.epam.cdp.selenium2.core.common.SpecialSymbols;
import com.epam.cdp.selenium2.core.configuration.GlobalConfiguration;
import com.epam.cdp.selenium2.core.results.logger.Logger;

/**
 * Parser for user's XML file with options. DTD for XML is {@link OptionsScheme.dtd}
 * 
 * @author yyudzitski
 */
public class OptionsParser extends DefaultHandler
{
  private Option currentOption;

  private List<Parameter> currentParameters;

  private Parameter currParam;

  private static final String OPTION_NAME = "option";

  private static final String PARAMETER_NAME = "parameter";

  private static final String NAME_ATTR = "name";

  private static final String VALUE_ATTR = "value";

  private static final String END_PARSING = "<<-- Parsed ";

  @Override
  public void startDocument()
  {
  }

  @Override
  public void endDocument()
  {
    Logger.debug( END_PARSING );
  }

  @Override
  public void startElement( String uri, String localName, String qName, Attributes attrs )
  {
    if( qName.equals( OPTION_NAME ) )
    {
      currentOption = new Option();
      currentOption.setOptionName( attrs.getValue( SpecialSymbols.EMPTY.toString(), NAME_ATTR ) );
      currentParameters = new ArrayList<Parameter>();
    }
    if( qName.equals( PARAMETER_NAME ) )
    {
      currParam = new Parameter();
      currParam.setName( attrs.getValue( SpecialSymbols.EMPTY.toString(), NAME_ATTR ) );
      currParam.setValue( attrs.getValue( SpecialSymbols.EMPTY.toString(), VALUE_ATTR ) );
    }
  }

  @Override
  public void endElement( String uri, String localName, String qName )
  {
    if( qName.equals( OPTION_NAME ) )
    {
      currentOption.setOptionParameters( currentParameters );
      GlobalConfiguration.getInstance().getOptionsConfiguration().addOption( currentOption );
      currentOption = null;
      currentParameters = null;
    }
    if( qName.equals( PARAMETER_NAME ) )
    {
      currentParameters.add( currParam );
      currParam = null;
    }
  }
}